# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
from pymongo import MongoClient


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
蝉妈妈-获取抖音接口
https://www.chanmama.com/
账号:17365997612
密码:abc123
"""

class ChanMaMa():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # 'User-Agent': ua.random,
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6MTAwMDAsImV4cGlyZV90aW1lIjoxNTkxNDcwMDAwLCJpYXQiOjE1OTA4OTk5NzAsImlkIjo1MjQ0OTV9._7d5x48lmpC0uKgGXtwG7Fi9mO1mtPPrSRZso3QRZ8I',
            'Connection': 'keep-alive',
            'DNT': '1',
            'Host': 'api-service.chanmama.com',
            'Origin': 'https://www.chanmama.com',
            'Referer': 'https://www.chanmama.com/authorDetail/58325035431',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'

        }

    # 查询排行
    def get_contents(self, cursor):
        postData = {
            'page': cursor,
            'category': '网红美女',
            'product_category':'',
            'keyword':'',
            'gender': '-1',
            'age':'',
            'follower_count':'',
            'product_platform':'',
            'province':'',
            'is_share_rank': '0',
            'contact': '0',
            'is_commerce': '0',
            'verification_type': '0',
            'sort': 'inc_follower',
            'size': '30',
            'order_by': 'desc'
        }
        url = f"https://api-service.chanmama.com/v1/home/author/search"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        data_json = json.loads(html.text)
        for d in data_json['data']['list']:
            dict_data = dict()
            dict_data['author_id'] = d['author_id']  # 抖音id
            dict_data['unique_id'] = d['unique_id']  # unique_id
            dict_data['nickname'] = d['nickname']  # 用户昵称
            dict_data['gender'] = d['gender']  # 性别 1女
            dict_data['follower_count'] = d['follower_count']  # 总粉丝数
            dict_data['total_favorited'] = d['total_favorited']  # 总点赞数
            dict_data['aweme_count'] = d['aweme_count']  # 视频总数
            print(str(dict_data))
            # self.get_user("58958068057")

    # 根据抖音id获取用户信息
    def get_user(self, id):
        postData = {
            'author_id': id  # '58958068057'
        }
        url = "https://api-service.chanmama.com/v1/home/author/info"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        data_json = json.loads(html.text)
        dict_data = dict()
        dict_data['author_id'] = data_json['data']['author_id']  # 抖音id
        dict_data['unique_id'] = data_json['data']['unique_id']  # unique_id
        dict_data['nickname'] = data_json['data']['nickname']  # 用户昵称
        dict_data['city'] = data_json['data']['city']  # 城市
        dict_data['birthday'] = data_json['data']['birthday']  # 生日
        dict_data['gender'] = data_json['data']['gender']  # 性别 1女
        dict_data['signature'] = data_json['data']['signature']  # 简介
        dict_data['url'] = data_json['data']['url']  # 分享地址
        dict_data['manual_label'] = data_json['data']['manual_label']  # 分类标签
        dict_data['verify_name'] = data_json['data']['verify_name']  # 认证标签
        dict_data['follower_count'] = data_json['data']['follower_count']  # 总粉丝数
        dict_data['total_favorited'] = data_json['data']['total_favorited']  # 总点赞数
        dict_data['total_share'] = data_json['data']['total_share']  # 总转发数
        dict_data['total_comment'] = data_json['data']['total_comment']  # 总评论数
        dict_data['aweme_count'] = data_json['data']['aweme_count']  # 视频总数
        print(str(dict_data))


    # 根据抖音id获取视频信息
    def get_video(self, id, current):
        postData = f'{{"author_id":"{id}","goods_relatived":0,"sort":"time","keyword":"","page":{current},"category":"","page_size":8,"filter_delete":0}}'
        url = "https://api-service.chanmama.com/v1/home/author/awemeList"
        html = HttpUtils.do_request("POST", url , self.headers, postData)
        data_json = json.loads(html.text)
        totalPage = data_json['page_info']['totalPage']  # 总页数
        for d in data_json['data']['search_results']:
            dict_data = dict()
            dict_data['author_id'] = d['aweme_info']['author_id']  # 抖音id
            dict_data['aweme_create_time'] = d['aweme_info']['aweme_create_time']  # 发布时间
            dict_data['aweme_create_time'] = d['aweme_info']['aweme_create_time']  # 发布时间
            dict_data['aweme_id'] = d['aweme_info']['aweme_id']  # 视频id
            dict_data['aweme_title'] = d['aweme_info']['aweme_title']  # 标题
            dict_data['aweme_url'] = d['aweme_info']['aweme_url']  # 视频分享地址
            dict_data['comment_count'] = d['aweme_info']['comment_count']  # 评论数量
            dict_data['digg_count'] = d['aweme_info']['digg_count']  # 点赞数量
            dict_data['share_count'] = d['aweme_info']['share_count']  # 转发数量
            dict_data['download_count'] = d['aweme_info']['download_count']  # 下载量
            dict_data['duration'] = d['aweme_info']['duration']  # 视频时长
            print(str(dict_data))
        # 翻页
        if current < totalPage:
            self.get_video(id, current + 1)


if __name__ == '__main__':
    chamama = ChanMaMa()
    # 查询排行
    for i in range(1, 3):
        print(f"============第【{i}】页=============")
        chamama.get_contents(i)

    # 根据抖音用户id获取用户信息
    chamama.get_user("58958068057")

    # 根据抖音用户id获取视频信息
    chamama.get_video("58958068057", 1)